import React, { FC, useEffect, useState, useRef, useMemo } from "react";
import { useSearchParams } from "react-router-dom";
import { useTitle, useRequest, useDebounceFn } from "ahooks";
import { Empty, Spin, Typography } from "antd";
import { getQuestionListService } from "../../services/question";
import QuestionCard from "../../components/QuestionCard";
import ListSearch from "../../components/ListSearch";
import styles from "./Common.module.scss";
import { LIST_PAGE_SIZE, LIST_SEARCH_PARAM_KEY } from "../../constant";

const { Title } = Typography;
const List: FC = () => {
  useTitle("星瑞问卷 - 我的问卷");
  const [started, setStarted] = useState(false); //是否开始加载 （防抖有延迟时间）
  const [page, setPage] = useState(0); //List 内部数据不在url 上体现
  const [list, setList] = useState([]); //上拉加载更多 累计数据
  const [total, setTotal] = useState(0); 
  const haveMoreData = total > list.length; //没有更多的，
  const [searchParams] = useSearchParams();
  const keyword =searchParams.get(LIST_SEARCH_PARAM_KEY)
  //keyword 变化时候 重置信息
  useEffect(()=>{
    setStarted(false)
    setPage(1)
    setList([])
    setTotal(0)
  },[keyword])
  //真正加载
  const { run: load, loading } = useRequest(
    async () => {
      const data = await getQuestionListService({
        page,
        pageSize: LIST_PAGE_SIZE,
        keyword: searchParams.get(LIST_SEARCH_PARAM_KEY) || "",
      });
      return data;
    },
    {
      manual: true,
      onSuccess(result) {
        const { list :l= [], total = 0 } = result;
        setList(list.concat(l)); //累计
        setTotal(total);
        setPage(page+1)
      },
    }
  );
  //尝试去触发加载 - 防抖
  const containerRef = useRef<HTMLDivElement>(null);
  const { run: tryLoadMore } = useDebounceFn(
    () => {
      const elem = containerRef.current;
      if (elem == null) return;
      const domRect = elem.getBoundingClientRect();
      if (domRect == null) return;
      const { bottom } = domRect;
      if (bottom < document.body.clientHeight) {
        load(); //真正加载数据
        setStarted(true)
      }
    },
    {
      wait: 1000,
    }
  );
  //当页面加载或者 url 参数变化时候 触发加载
  useEffect(() => {
    tryLoadMore(); //初始化加载
  }, [searchParams, tryLoadMore]);
  //当页面滚动时，尝试触发加载器
  useEffect(() => {
    if (haveMoreData) {
      window.addEventListener("scroll", tryLoadMore);
    }
    return () => {
      //解绑事件
      window.removeEventListener("scroll", tryLoadMore);
    };
  }, [haveMoreData, searchParams, tryLoadMore]);

  //LoadMore
  const LoadMoreConentEle=useMemo(()=>{
    if(!started||loading )return <Spin></Spin>
    if(total===0) return <Empty description='暂无数据'/>
    if(!haveMoreData) return <span>没有更多了</span>
    return <span>上滑加载更多</span>
  },[started, loading, total, haveMoreData])
  return (
    <>
      <div className={styles.header}>
        <div className={styles.left}>
          <Title level={3}>我的问卷</Title>
        </div>
        <div className={styles.right}>
          <ListSearch />
        </div>
      </div>
      <div className={styles.content}>
        {/* 问卷列表 */}
        {
          list.length > 0 &&
          list.map((q: any) => {
            const { _id } = q;
            return <QuestionCard {...q} key={_id} />;
          })}
      </div>
      <div className={styles.footer}>
        <div ref={containerRef}>{LoadMoreConentEle}</div>
      </div>
    </>
  );
};
export default List;
